import {
  addRoleUser,
  delRoleUser,
  queryRoleUserList,
  updateRoleUser,
} from "@/services/roles";
import { PlusOutlined } from "@ant-design/icons";
import {
  ModalForm,
  PageContainer,
  ProFormSelect,
  ProFormSwitch,
  ProFormText,
  ProTable,
} from "@ant-design/pro-components";
import { Button, Card, Form, message, Popconfirm, Space, Tag } from "antd";
import dayjs from "dayjs";
import { useEffect, useRef, useState } from "react";

const RoleManagement = () => {
  const [open, setOpen] = useState(false);
  const [currentType, setCurrentType] = useState(""); //当前状态
  const [currentData, setCurrentData] = useState<any>(null); //当前状态
  const actionRef: any = useRef(null);
  const [form] = Form.useForm();
  const columns: any = [
    {
      title: "用户名称",
      dataIndex: "nickname",
      ellipsis: true,
      search: false,
      formItemProps: {
        rules: [
          {
            required: true,
            message: "用户名称为必填项",
          },
        ],
      },
    },
    {
      title: "登录账号",
      dataIndex: "username",
      ellipsis: true,
      search: false,
    },
    {
      title: "当前角色",
      dataIndex: "authority",
      ellipsis: true,
      search: false,
      valueEnum: {
        1: { text: <Tag color="blue">超级管理员</Tag> },
        2: { text: <Tag color="blue">出库管理员</Tag> },
        3: { text: <Tag color="blue">人事管理员</Tag> },
        4: { text: <Tag color="blue">采购管理员</Tag> },
      },
    },
    {
      title: "状态",
      dataIndex: "status",
      valueType: "select",
      search: false,
      valueEnum: {
        1: { text: <Tag color="green">启用</Tag>, status: "Success" },
        0: { text: <Tag color="red">禁用</Tag>, status: "Error" },
      },
    },
    {
      title: "创建时间",
      dataIndex: "created_at",
      search: false,
      render: (time: string) => dayjs(Number(time) * 1000).format("YYYY-MM-DD"),
    },
    {
      title: "最后登录时间",
      dataIndex: "last_login",
      search: false,
      render: (time: string) =>
        dayjs(Number(time) * 1000).format("YYYY-MM-DD hh:mm:ss"),
    },
    {
      title: "操作",
      valueType: "option",
      key: "option",
      with: 100,
      render: (text: any, record: any) => (
        <Space>
          <a onClick={() => handleEdit(record)}>编辑</a>
          <Popconfirm
            title="提示"
            description="确认删除该用户吗？"
            onConfirm={() => handleDel(record.id)}
            okText="确认"
            cancelText="取消"
          >
            <a>删除</a>
          </Popconfirm>
        </Space>
      ),
    },
  ];

  useEffect(() => {
    if (open) {
      if (currentData) form.setFieldsValue(currentData);
    } else {
      form.resetFields();
    }
  }, [open, currentData]);

  const handleSubmit = async (values: any) => {
    const params = {
      ...values,
      id: currentType === "edit" ? values?.id : undefined,
    };
    const res =
      currentType === "edit"
        ? await updateRoleUser(params)
        : await addRoleUser(params);
    if (res.success) {
      message.success("操作成功");
      actionRef?.current?.reload();
      setOpen(false);
    } else {
      message.error("操作失败，请联系管理员");
    }
  };
  const fetchData = async (params: any) => {
    const res = await queryRoleUserList({
      page: 1,
      pagesize: 999,
    });
    return {
      data: res?.result?.data || [],
      total: res?.total || 0,
      success: true,
    };
  };

  const handleEdit = (value: any) => {
    setOpen(true);
    setCurrentData(value);
    setCurrentType("edit");
  };
  const handleDel = async (id: number) => {
    const res = await delRoleUser({ id });
    if (res?.success) {
      message.success("操作成功");
      actionRef?.current?.reload();
    } else {
      message.error("操作失败，请联系管理员");
    }
  };

  return (
    <PageContainer>
      <Card>
        <ProTable
          search={false}
          headerTitle="用户列表"
          actionRef={actionRef}
          request={fetchData}
          rowKey="id"
          options={false}
          toolBarRender={() => [
            <Button
              key="button"
              icon={<PlusOutlined />}
              type="primary"
              onClick={() => {
                setOpen(true);
                setCurrentType("create");
              }}
            >
              新建用户
            </Button>,
          ]}
          columns={columns}
        />

        <ModalForm
          form={form}
          title={currentType === "edit" ? "编辑用户" : "新建用户"}
          width="600px"
          open={open}
          onFinish={handleSubmit}
          onOpenChange={(open) => {
            setOpen(open);
            if (!open) {
              setCurrentData(null);
              setCurrentType("");
            }
          }}
        >
          <ProFormText name="id" label="id" hidden />
          <ProFormText
            name="nickname"
            label="用户名称"
            placeholder="请输入用户名称"
            rules={[{ required: true, message: "请输入用户名称" }]}
          />
          <ProFormText
            name="username"
            label="登录账号"
            placeholder="请输入登录账号"
            rules={[
              { required: true, message: "请输入登录账号" },
              {
                validator: (_: any, value: string) => {
                  if (/\s/.test(value)) {
                    return Promise.reject(new Error("登录账号不能包含空格"));
                  } else {
                    return Promise.resolve();
                  }
                },
              },
            ]}
          />
          <ProFormText
            name="password"
            label="登录密码"
            placeholder="请输入登录密码"
            rules={[
              { required: true, message: "请输入登录密码" },
              {
                validator: (_: any, value: string) => {
                  if (/\s/.test(value)) {
                    return Promise.reject(new Error("密码中不能包含空格"));
                  } else {
                    return Promise.resolve();
                  }
                },
              },
            ]}
          />
          <ProFormSwitch
            name="status"
            label="状态"
            checkedChildren="启用"
            unCheckedChildren="禁用"
            rules={[{ required: true }]}
            initialValue={true}
          />
          <ProFormSelect
            name="authority"
            label="权限分配"
            placeholder="请选择权限"
            options={[
              {
                label: "超级管理员",
                value: 1,
              },
              {
                value: 2,
                label: "出库管理员",
              },
              {
                value: 3,
                label: "人事管理员",
              },
              {
                value: 4,
                label: "采购管理员",
              },
            ]}
            rules={[{ required: true, message: "请选择权限" }]}
          />
        </ModalForm>
      </Card>
    </PageContainer>
  );
};

export default RoleManagement;
